#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2018/10/31
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :Ind_UnpaidCreditCnt.py
# @Software  :PyCharm

'''eof
name: 申请人未结清信用贷款笔数
code: Ind_UnpaidCreditCnt
tableName:
columnName:
groups:个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

"""
指标值 = 统计“担保方式描述”为信用/免担保的未结清贷款笔数 
Factor =select count * from 贷款信息明细 
where GuaranteeType==“信用/免担保”and 
账户状态 in（“正常”、“逾期”、“呆账”）and 合同总额>50000；
"""

import json
import sys

# reload(sys)
# sys.setdefaultencoding('utf-8')


# with open('data.json', 'r') as ICR_load:
#     IC = json.load(ICR_load)['IC']



def FormatData(tableName):
    """
    数据解析
    :param tableName: 目标字段
    :return: 
    """

    try:
        # ecr是最外面一层表里面的
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
        return [{}]


def ConvertDataType(dataValue, dataType):
    """
    数据格式转换
    :param dataValue: 
    :param dataType: 数据类型
    :return: 
    """
    returnData = None
    if dataType == 'float':
        try:
            returnData = float(dataValue) if float(dataValue) >= 0 else None
        except:
            returnData = None
    elif dataType == 'None':
        returnData = 0 if dataValue is None else dataValue
    elif dataType == 'str':
        try:
            returnData = dataValue if len(dataValue) >= 0 else None
        except:
            returnData = None

    return returnData

def IndexJudge(GuaranteeTypeSet, StateSet, CreditLimitAmountSet):
    """
    指标逻辑判断
    :param GuaranteeTypeSet: 担保方式描述
    :param StateSet: 帐户状态
    :param CreditLimitAmountSet: 
    :return: 
    """

    if GuaranteeTypeSet == u'信用/免担保' and StateSet in [u'正常', u'逾期', u'呆账'] and CreditLimitAmountSet > 50000:
        Count = 1
    else:
        Count = 0

    return Count


def IndexJudgeSum(dataList):
    """
    指标条件判别
    :param dataList: 
    :param creditType: 
    :return: 
    """

    infoCount = []
    for i in range(len(dataList)):
        GuaranteeTypeInfo = ConvertDataType(dataList[i].get('GuaranteeType'), 'str')
        StateInfo = ConvertDataType(dataList[i].get('State'), 'str')
        CreditLimitAmountInfo = ConvertDataType(dataList[i].get('CreditLimitAmount'), 'float')
        infoCount.append(IndexJudge(GuaranteeTypeInfo, StateInfo, CreditLimitAmountInfo))

    return infoCount



def Ind_UnpaidCreditCnt():
    """
    申请人在申请时合同总额大于五万的信用贷款的未结清贷款笔数>3，则拒绝
    :return: 
    """

    try:
        # 贷款信息  信息汇总
        ICRLoanInfo002Loan = FormatData("ICRLoanInfo002*Loan")

        if ICRLoanInfo002Loan == [{}]:
            return u'缺失值'

        else:
            # 统计指标
            IndexCount = IndexJudgeSum(ICRLoanInfo002Loan)

            return sum(IndexCount)

    except:
        # 异常提示或者异常出口
        return None

result = Ind_UnpaidCreditCnt()


